import React from 'react';
import {Link} from 'react-router';

var qiniu_public_url = "http://ohqm88vkq.bkt.clouddn.com/";
var qiniu_private_url = "http://ohqmxaqtq.bkt.clouddn.com/";
var attachment_server_url = "http://a8-domain.pagoda.com.cn:20101";
class AttachmentMgt extends  React.Component{
    /*static defaultProps = {
        imgClass: "common-img",
        labels:['身份证正面','身份证反面','营业执照']
    };*/
    constructor(props){
        super(props);
        var myself = this;
        this.dataChanged = false;       //记住数据有无变化
        this.curSelected = -1;//记住当前选择的项，主要用于更换照片
        this.state = {
            files:[]
        }
        this.uploader = null;
        this.componentDidMount = this.componentDidMount.bind(this);
        this.addFileToList = this.addFileToList.bind(this);
        this.save = this.save.bind(this);
        this.handleDeleteA = this.handleDeleteA.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.changeFileInList = this.changeFileInList.bind(this);
        this.qiniuCfg = {
            runtimes: 'html5,flash,html4',      // 上传模式，依次退化
            //browse_button: 'pickfiles',         // 上传选择的点选按钮，必需
            //uptoken:token,
            get_new_uptoken: false,             // 设置上传文件的时候是否每次都重新获取新的uptoken
            domain: 'http://qiniu-plupload.qiniudn.com/',     // bucket域名，下载资源时用到，必需
            //container: 'container',             // 上传区域DOM ID，默认是browser_button的父元素
            max_file_size: '100mb',             // 最大文件体积限制
            flash_swf_url: 'path/of/plupload/Moxie.swf',  //引入flash，相对路径
            max_retries: 3,                     // 上传失败最大重试次数
            //dragdrop: true,                     // 开启可拖曳上传
            //drop_element: 'container',          // 拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
            chunk_size: '4mb',                  // 分块上传时，每块的体积
            auto_start: true,                   // 选择文件后自动上传，若关闭需要自己绑定事件触发上传,
            scope:"bucket",
            unique_names:true,
            log_level:6,
            init: {
                'FilesAdded': function(up, files) {
                                plupload.each(files, function(file) {
                                // 文件添加进队列后，处理相关的事情
                                });
                        },
                'BeforeUpload': function(up, file) {
                            // 每个文件上传前，处理相关的事情
                        },
                'UploadProgress': function(up, file) {
                            // 每个文件上传时，处理相关的事情
                        },
                'FileUploaded': function(up, file, info) {
                            var  res = JSON.parse(info);
                            if(res != null){
                                myself.addFileToList(myself.refs.labelInput.value,res.key);
                            }
                        },
                'Error': function(up, err, errTip) {
                        //上传出错时，处理相关的事情
                        },
                'UploadComplete': function(evt,uploadedFiles) {
                        //队列文件处理完毕后，处理相关的事情
                            console.log("upload complete" + uploadedFiles.length);
                            console.log(uploadedFiles[0]);
                        },
                'Key': function(up, file) {
                        // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
                        // 该配置必须要在unique_names: false，save_key: false时才生效
                            var key = "";
                            return key
                        }
                }
            }
    
        
    }
    save(){
        var res = [];
        $.each(this.state.files,function(idx,item){
            if(item.deleted) {
                //todo: delete the file
            }else{
                res.push(item);
            }
        });
        return item;
    }
    addFileToList(label,file){
        var myself = this;
        var param = {
                        fileUseLabel:label,
                        fileKey:file,
                        bucketname:'public'
                    };
        var files = myself.state.files;
        if(files == undefined) files = [];
        files.unshift(param);
        this.dataChanged = true;
        myself.setState({files:files});
    }
    changeFileInList(file){//变更文件在交互上很难做好，暂时屏蔽这个功能
        /*if(this.curSelected != -1){
            var files = this.state.files;
            files[this.curSelected].fileKey = file;//todo, 需要删除老的资源
        }
        this.dataChanged = true;
        this.setState({files:files});
        this.curSelected = -1;*/
    }
    handleChange(evt){//变更文件在交互上很难做好，暂时屏蔽这个功能
        /*this.curSelected = (evt.target.parentNode.id);  //记住当前选择的项，方便更换对象附件
        $(this.refs.pickfiles).trigger(evt); //激活上传操作
        */
    }
    handleDeleteA(evt){
        var files = this.state.files;
        if(evt.target.parentNode.id < files.length ){
                files[evt.target.parentNode.id].deleted = true;
        }
        this.dataChanged = true;
        this.setState({files:files});
    }
    getTokenMessage(){
        var dfd = $.Deferred();
        $.post({
            url:attachment_server_url + '/fileMgr/qiniu/getUpToken',
            async:false,
            data:JSON.stringify({
                bucketname:'public'
                }),
            contentType : 'application/json',
            dataType: 'json',
            success:function (data) {
                {
                    dfd.resolve(data.data);
                }
            }
        });
        return dfd;
    }
    componentDidMount(){
        var myself = this;
        //取得token后初始化qiniu
        this.getTokenMessage().done(function(token){
            //引入Plupload 、qiniu.js后
            myself.qiniuCfg.uptoken = token;
            myself.qiniuCfg.browse_button = 'pickfiles';//plupload接管这个按钮
            myself.uploader = Qiniu.uploader(myself.qiniuCfg);
        })
    }
    render(){
        var files = [];
        var labels = [];
        {
            var myself = this;
            $.each(this.state.files,function(idx,item){
                if(!item.hasOwnProperty('deleted')){
                    //li 记住是项目对应的索引
                    files.push(<li id={idx}
                    key={item.fileKey}><img class={myself.props.imgClass} src={qiniu_public_url + "/" + item.fileKey} onClick={myself.handleChange}/>{item.fileUseLabel} 
                                                <button onClick={myself.handleDeleteA}>删除</button></li>)
                }
            });
        }
        $.each(this.props.labels,function(idx,item){
            labels.push(<option>{item}</option>)
        });
        return (<div><div id='container'>
            <input list='attachment_label' ref='labelInput'></input>
            <datalist id='attachment_label'>{labels}</datalist>
            <button id='pickfiles' ref='pickfiles' >上载</button>
            </div>
            <div><ul>
            {files}
            </ul>
            </div>
        </div>);
    }
}
export default AttachmentMgt;